<script setup>
import ip from '@/utils/baseURL.js';
import { ref, computed, onMounted } from 'vue'
import { Trophy, Reading, Medal, Star, Picture } from '@element-plus/icons-vue'
import axios from 'axios'

// 状态变量
const activeTab = ref('all')
const selectedYear = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const allHonours = ref([]) // 存储所有荣誉数据
const honours = ref([]) // 当前显示的荣誉数据

// 获取荣誉数据
const getHonors = async () => {
    try {
        const response = await axios.get(ip + '/inter/honor/get')
        if (response.data.code === 200) {
            // 处理返回的数据
            allHonours.value = response.data.data.records.map(honor => {
                // 处理日期格式，精确到日
                const time = honor.time || [2024, 1, 1]
                const dateStr = `${time[0]}-${String(time[1]).padStart(2, '0')}-${String(time[2] || 1).padStart(2, '0')}`
                
                // 确定荣誉类型映射
                let type = 'other'
                if (honor.type.includes('科研')) {
                    type = 'research'
                } else if (honor.type.includes('教学')) {
                    type = 'teaching'
                }
                
                return {
                    id: honor.id,
                    title: honor.title,
                    type: type,
                    date: dateStr,  // 现在格式为 YYYY-MM-DD
                    year: time[0],
                    description: honor.briInfo,
                    winners: honor.winners,
                    image: honor.image || '/images/honours/default.jpg' // 默认图片
                }
            })
            
            applyFilters() // 应用筛选并更新分页数据
        }
    } catch (error) {
        console.error('获取荣誉数据失败:', error)
        // 使用默认数据
        allHonours.value = [
            {
                id: 1,
                title: '国家科技进步奖二等奖',
                type: 'research',
                date: '2024-01-15',  // 更新为精确到日的格式
                year: 2024,
                description: '在农业智能装备领域取得重大突破，研发出具有自主知识产权的智能农业机器人系统',
                winners: '张三、李四、王五',
                image: '/images/honours/research-award.jpg'
            }
        ]
        applyFilters()
    }
}

// 应用筛选并更新分页
const applyFilters = () => {
    let filtered = [...allHonours.value]

    // 根据类型筛选
    if (activeTab.value !== 'all') {
        filtered = filtered.filter(honour => honour.type === activeTab.value)
    }
    
    // 根据年份筛选
    if (selectedYear.value) {
        filtered = filtered.filter(honour => honour.year === selectedYear.value)
    }

    // 按日期倒序排序
    filtered = filtered.sort((a, b) => {
        if (b.year !== a.year) {
            return b.year - a.year
        }
        return b.date.localeCompare(a.date)
    })

    // 更新总数
    total.value = filtered.length
    
    // 计算当前页数据
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    honours.value = filtered.slice(startIndex, endIndex)
    
    // 如果当前页没有数据且不是第一页，则回到第一页
    if (honours.value.length === 0 && currentPage.value > 1) {
        currentPage.value = 1
        applyFilters() // 重新应用筛选
    }
}

// 筛选荣誉 - 仅用于计算年份分组
const filteredHonours = computed(() => honours.value)

// 获取排序后的年份列表
const sortedYears = computed(() => {
    const years = new Set(honours.value.map(honour => honour.year))
    return Array.from(years).sort((a, b) => b - a)
})

// 年份选项 - 使用所有荣誉数据计算年份选项
const years = computed(() => {
    const years = new Set(allHonours.value.map(honour => honour.year))
    return Array.from(years).sort((a, b) => b - a)
})

// 获取指定年份的荣誉
const getYearHonours = (year) => {
    return filteredHonours.value
        .filter(honour => honour.year === year)
        .sort((a, b) => b.date.localeCompare(a.date))
}

// 获取荣誉类型图标
const getHonourTypeIcon = (type) => {
    const icons = {
        research: Trophy,
        teaching: Reading,
        other: Medal
    }
    return icons[type] || Star
}

// 获取荣誉类型颜色
const getHonourTypeColor = (type) => {
    const colors = {
        research: '#F56C6C',
        teaching: '#67C23A',
        other: '#E6A23C'
    }
    return colors[type] || '#909399'
}

// 获取荣誉类型标签样式
const getHonourTypeTag = (type) => {
    const tags = {
        research: 'danger',
        teaching: 'success',
        other: 'warning'
    }
    return tags[type] || 'info'
}

// 获取荣誉类型标签文本
const getHonourTypeLabel = (type) => {
    const labels = {
        research: '科研奖项',
        teaching: '教学成果',
        other: '其他荣誉'
    }
    return labels[type] || '其他'
}

// 事件处理
const handleTabClick = () => {
    currentPage.value = 1
    // 当切换分类时自动清空年份选择
    selectedYear.value = ''
    applyFilters()
}

const handleYearChange = () => {
    currentPage.value = 1
    applyFilters()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    applyFilters()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    applyFilters()
}

// 页面加载时获取数据
onMounted(() => {
    getHonors()
})
</script>

<template>
    <div class="honours-container">
        <div class="main-content">
            <!-- 页面标题 -->
            <div class="page-header">
                <h1>实验室荣誉</h1>
            </div>

            <!-- 荣誉分类标签和年份筛选 -->
            <div class="filter-section">
                <div class="honour-tabs">
                    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                        <el-tab-pane label="全部荣誉" name="all"></el-tab-pane>
                        <el-tab-pane label="科研奖项" name="research"></el-tab-pane>
                        <el-tab-pane label="教学成果" name="teaching"></el-tab-pane>
                        <el-tab-pane label="其他荣誉" name="other"></el-tab-pane>
                    </el-tabs>
                </div>
                <div class="year-filter">
                    <el-select v-model="selectedYear" placeholder="选择年份" clearable @change="handleYearChange">
                        <el-option
                            v-for="year in years"
                            :key="year"
                            :label="year + '年'"
                            :value="year"
                        />
                    </el-select>
                </div>
            </div>

            <!-- 荣誉列表 -->
            <div class="honour-list">
                <div v-for="year in sortedYears" :key="year" class="year-group">
                    <div class="year-header">{{ year }}年</div>
                    <el-card v-for="honour in getYearHonours(year)" :key="honour.id" class="honour-item">
                        <div class="honour-content">
                            <div class="honour-image">
                                <el-image 
                                    :src="honour.image" 
                                    :preview-src-list="[honour.image]"
                                    fit="cover"
                                    class="honour-img"
                                >
                                    <template #error>
                                        <div class="image-slot">
                                            <el-icon><Picture /></el-icon>
                                        </div>
                                    </template>
                                </el-image>
                            </div>
                            <div class="honour-info">
                                <h3 class="honour-title">{{ honour.title }}</h3>
                                <div class="honour-meta">
                                    <el-tag :type="getHonourTypeTag(honour.type)" size="small">
                                        {{ getHonourTypeLabel(honour.type) }}
                                    </el-tag>
                                    <span class="honour-date">{{ honour.date }}</span>
                                </div>
                               
                                <div class="honour-winners" v-if="honour.winners">
                                    <span class="winners-label">获奖人：</span>
                                    <span class="winners-list">{{ honour.winners }}</span>
                                </div>
                                <div class="honour-description" v-if="honour.description">
                                    {{ honour.description }}
                                </div>
                            </div>
                        </div>
                    </el-card>
                </div>
            </div>

            <!-- 分页器 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :total="total"
                    :page-sizes="[10, 20, 30, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.honours-container {
    width: 100%;
    
    .main-content {
        width: 85%;  // 与其他页面保持一致
        margin: 0 auto;
        padding: 40px 20px;
        box-sizing: border-box;
    }

    .page-header {
        margin-bottom: 40px;
        text-align: center;

        h1 {
            font-size: 36px;
            color: #333;
            margin: 0;
            position: relative;
            display: inline-block;
            padding-bottom: 15px;

            &::after {
                content: '';
                position: absolute;
                bottom: 0;
                left: 50%;
                transform: translateX(-50%);
                width: 60px;
                height: 4px;
                background-color: #86B943;
            }
        }
    }

    .filter-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        
        .honour-tabs {
            flex: 1;
            margin-bottom: 0;
        }

        .year-filter {
            width: 180px;
            margin-bottom: 0;
        }
    }

    .honour-list {
        .year-group {
            margin-bottom: 40px;

            .year-header {
                font-size: 24px;
                color: #333;
                margin-bottom: 20px;
                padding-left: 15px;
                border-left: 4px solid #86B943;
            }
        }

        .honour-item {
            margin-bottom: 20px;
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .honour-content {
                display: flex;
                gap: 30px;

                .honour-image {
                    width: 300px;
                    height: 200px;
                    overflow: hidden;
                    border-radius: 8px;
                    flex-shrink: 0;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

                    .honour-img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                        transition: transform 0.3s ease;

                        &:hover {
                            transform: scale(1.05);
                        }
                    }

                    .image-slot {
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        width: 100%;
                        height: 100%;
                        background: #f5f7fa;
                        color: #909399;
                        font-size: 30px;
                    }
                }

                .honour-info {
                    flex: 1;

                    .honour-title {
                        font-size: 18px;
                        color: #333;
                        margin: 0 0 10px 0;
                        font-weight: bold;
                    }

                    .honour-meta {
                        margin-bottom: 10px;
                        display: flex;
                        align-items: center;
                        gap: 15px;

                        .honour-date {
                            color: #999;
                            font-size: 14px;
                        }
                    }

                    .honour-description {
                        color: #666;
                        line-height: 1.6;
                        margin-top: 10px;
                        font-size: 14px;
                    }

                    .honour-winners {
                        color: #666;
                        font-size: 14px;

                        .winners-label {
                            color: #999;
                        }
                    }
                }
            }
        }
    }

    .pagination-container {
        margin-top: 30px;
        display: flex;
        justify-content: center;
    }
}
</style>